<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'cardd:kped:carddKped:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsCarddKpedCarddKpedForm">
  import { computed, ref, unref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { CarddKped, carddKpedForm, carddKpedSave } from '/@/api/cardd/kped/carddKped';
  import { dateUtil } from '/@/utils/dateUtil';
  import advancedFormat from 'dayjs/plugin/advancedFormat';

  dateUtil.extend(advancedFormat);

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('cardd.kped.carddKped');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<CarddKped>({} as CarddKped);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增开票额度') : t('编辑开票额度'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('开票单位'),
      field: 'kpedKpdw',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('开票年度'),
      field: 'kpedKpnd',
      component: 'DatePicker',
      componentProps: {
        maxlength: 100,
        picker: 'year',
        format: 'YYYY',
        valueFormat: 'YYYY',
      },
      required: true,
    },
    {
      label: t('开票类型'),
      field: 'kpedKplx',
      component: 'Select',
      componentProps: {
        dictType: 'car_kp_type',
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('开票月/季'),
      field: 'kpedKpyj',
      component: 'Select',
      componentProps: ({ formModel }) => {
        return {
          dictType: 'car_kp_zq',
          allowClear: true,
          onChange: (value: string) => {
            updateKpzqSchema(value);
          },
        };
      },
      required: true,
    },
    {
      label: t('开票周期'),
      field: 'kpedKpzq',
      component: 'DatePicker',
      componentProps: ({ formModel }) => {
        const picker = formModel.kpedKplx === '0' ? 'quarter' : 'month';
        return {
          maxlength: 8,
          picker: picker,
          format: picker == 'quarter' ? '[Q]Q' : 'MM月',
          valueFormat: 'M',
        };
      },
    },
    {
      label: t('金额'),
      field: 'kpedJe',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [
        {
          required: true,
          pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/,
          message: t('请输入一个数值'),
        },
      ],
    },
    {
      label: t('税额'),
      field: 'kpedSe',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      rules: [
        {
          pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/,
          message: t('请输入一个数值'),
        },
      ],
    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 600,
      },
      colProps: { lg: 24, md: 24 },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await carddKpedForm(data);
    record.value = (res.carddKped || {}) as CarddKped;
    record.value.__t = new Date().getTime();
    updateKpzqSchema(res?.carddKped.kpedKpyj);
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      // console.log('submit', params, data, record);
      const res = await carddKpedSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  function updateKpzqSchema(value: string) {
    console.log('updateKpzqSchema', value);
    const kpzq = {
      label: t('开票周期'),
      field: 'kpedKpzq',
      component: 'DatePicker',
      componentProps: {
        maxlength: 8,
      },
    } as FormSchema;
    if (value === '0') {
      kpzq.component = 'Select';
      kpzq.componentProps.dictType = 'car_quarter';
    } else {
      kpzq.componentProps.picker = 'month';
      kpzq.componentProps.format = 'MM月';
      kpzq.componentProps.valueFormat = 'M';
    }
    updateSchema(kpzq);
  }
</script>
